<template>
    <el-drawer
        v-model="isShow"
        :title="title"
        :destroy-on-close="true"
        size="50%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :show-close="false"
    >
        <el-form
            ref="queryFormRef"
            :model="queryForm"
            label-width="auto"
            :rules="queryFormRules"
        >
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="身份证：" required prop="idnumber">
                        <el-input v-model="queryForm.idnumber" placeholder="请填写重点对象的身份证号码"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="姓名：" required prop="name">
                        <el-input v-model="queryForm.name" placeholder="请填写重点对象姓名"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="性别：" required prop="sex">
                        <el-select
                            v-model="queryForm.sex"
                            placeholder="选择性别"
                        >
                            <el-option
                                v-for="item in nj_sex"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="预警级别：" required prop="warninglevel">
                        <el-select
                            v-model="queryForm.warninglevel"
                            placeholder="选择预警级别"
                        >
                            <el-option
                                v-for="item in nj_warning_level"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="状态：" required prop="state">
                        <el-select
                            v-model="queryForm.state"
                            placeholder="选择状态"
                        >
                            <el-option
                                v-for="item in sys_normal_disable"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="民族：">
                        <el-input v-model="queryForm.nation" placeholder="请填写重点对象名族"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="工作单位：">
                        <el-input v-model="queryForm.workplace" placeholder="请填写重点对象的工作单位"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="职务：">
                        <el-input v-model="queryForm.post" placeholder="请填写重点对象工作的职务"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="住址：">
                <el-input v-model="queryForm.address" placeholder="请填写重点对象的住址"/>
            </el-form-item>
            <el-form-item label="其他信息：">
                <el-input v-model="queryForm.detail" type="textarea" :rows="3" placeholder="其他信息"/>
            </el-form-item>
            <el-form-item label="照片：" required prop="photo">
                <el-upload
                    class="victor-uploader"
                    :show-file-list="false"
                    :before-upload="handleBeforeUpload"
                >
                    <img v-if="queryForm.photo" :src="queryForm.photo" class="avatar" alt=""/>
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus/>
                    </el-icon>
                    <template #tip>
                        <div class="el-upload__tip">
                            <p>图像要求：</p>
                            <ul>
                                <li>建议待检测的图像人脸角度上、下、左、右转向小于30度;</li>
                                <li>图像中人脸尺寸不小于80 x 80像素;</li>
                                <li>图像大小小于10MB;</li>
                                <li>图像清晰;</li>
                            </ul>
                        </div>
                    </template>

                </el-upload>
            </el-form-item>
        </el-form>

        <template #footer>
            <!-- 创建 -->
            <el-button type="primary" @click="createPersonHandle(queryFormRef)" v-if="isAdd">提交</el-button>
            <!-- 更新 -->
            <el-button type="primary" @click="updatePersonHandle" v-else>提交</el-button>
            <el-button @click="changeShowStatus">关闭</el-button>
        </template>

    </el-drawer>
</template>

<script setup>
import {Plus} from "@element-plus/icons-vue";
import {
    createKeyPersonManage,
    getKeyPersonManageInfo,
    updateKeyPersonManage
} from "@/api/PlanManage/KeyPersonManage.js";
import {ElMessage} from "element-plus";
import {useTemplateRef} from "vue";
import {validateIdCard} from "@/validate/validateIdCard.js";

const {proxy} = getCurrentInstance()
const {nj_sex, nj_warning_level, sys_normal_disable} = proxy.useDict('nj_sex', 'nj_warning_level', 'sys_normal_disable')

const isAdd = ref(true)
const isShow = ref(false)
const title = ref('重点管理对象')
const emit = defineEmits(['refresh-list'])
const defaultQueryForm = {
    // 身份证
    idnumber: '',
    name: '',
    // 性别
    sex: '1',
    // 预警级别
    warninglevel: '1',
    // 状态
    state: '0',
    // 民族
    nation: '',
    // 工作单位
    workplace: '',
    // 职务
    post: '',
    // 住址
    address: '',
    // 其他信息
    detail: '',
    // 图片地址
    photo: ''
}
const queryForm = ref({...defaultQueryForm});  // 初始化时用默认值

const queryFormRules = reactive({
    // 身份证
    idnumber: [
        {required: true, message: '请填写身份证号', trigger: 'blur'},
        {validator: validateIdCard, trigger: 'blur'}
    ],
    // 姓名
    name: [
        {required: true, message: '请填写姓名', trigger: 'blur'},
    ],
    // 性别
    sex: [
        {required: true, message: '请选择性别', trigger: 'blur'},
    ],
    // 预警级别
    warninglevel: [
        {required: true, message: '请选择预警级别', trigger: 'blur'},
    ],
    // 状态
    state: [
        {required: true, message: '请选择状态', trigger: 'blur'},
    ],
    // 图片
    photo: [
        {required: true, message: '请上传图片', trigger: 'blur'},
    ]
})
const queryFormRef = useTemplateRef('queryFormRef')

// 变更显示状态
const changeShowStatus = () => {
    isShow.value = !isShow.value
    if (!isShow.value) {
        resetQueryForm();  // 关闭时重置表单
    }
}

// 重置表单函数
const resetQueryForm = () => {
    queryForm.value = {...defaultQueryForm};  // 重置 queryForm 为默认状态
};

const showAddPersonMange = () => {
    resetQueryForm()
    changeShowStatus()
    title.value = '新增重点管理对象'
}

const showEditPersonMange = (data) => {
    changeShowStatus()
    isAdd.value = false
    title.value = '编辑重点管理对象'
    // queryForm.value = JSON.parse(JSON.stringify(data))
    getDetail(data.peopleId)
}

defineExpose({showAddPersonMange, showEditPersonMange})

// 获取详情
const getDetail = async (id) => {
    const res = await getKeyPersonManageInfo(id)
    queryForm.value = res.data
}
// 图片上传
const handleBeforeUpload = async (file) => {
    const types = ['image/jpeg', 'image/png', 'image/jpg']
    const msg = '上传图片只能是 JPG/PNG格式!'
    const isImage = types.includes(file.type)

    console.log(file)
    const isLimit = file.size / 1024
    if (isLimit < 10) {
        ElMessage.error('图片不能小于10KB')
        return false
    }

    const checkImageSize = (file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = (e) => {
                queryForm.value.photo = e.target.result;
                const img = new Image();
                img.onload = () => {
                    const width = img.width;
                    const height = img.height;
                    return resolve(width < 80 || height < 80);
                };
                img.onerror = () => {
                    reject(false); // 图片加载失败也视为无效尺寸
                };
            };
        });
    };

    const isValidSize = checkImageSize(file);
    if (!isValidSize) {
        ElMessage.error('上传图片尺寸不能小于80x80像素')
        return false;
    }

    return false; // 阻止默认上传行为
}

// 创建重点管理对象
const createPersonHandle = async (elForm) => {
    if (!elForm) return
    await elForm.validate(async (valid, fields) => {
        if (valid) {
            await createKeyPersonManage(queryForm.value)
            emit('refresh-list')
            changeShowStatus()
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 更新重点管理对象
const updatePersonHandle = async () => {
    await updateKeyPersonManage(queryForm.value)
    emit('refresh-list')
    changeShowStatus()
}
</script>

<style scoped lang="scss">
.victor-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.victor-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.victor-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>